<template>
  <div>
    <ul>
      <li v-for="(item, index) in cities" :key="index" v-if="item.list.length !== 0" class="customlist">
<!--        <el-checkbox :indeterminate="item.isIndeterminate" v-model="item.checked"-->
<!--                     @change="handleCheckAllChange(index, $event)">{{item.name}}-->
<!--        </el-checkbox>-->
        <!-- <div style="margin: 15px 0;"></div> -->
        <p>
          <el-checkbox v-for="(items , i) in item.list" v-model="items.checked" :label="items.name" :key="i"
                       @change="handleCheckedCitiesChange(index, items.sobId, $event)">{{items.name}}
          </el-checkbox>
        </p>
      </li>
    </ul>
  </div>
</template>
<script>
  const cityOptions = [{
    name: 'a1',
    list: [{name: '上海', sobId: '1'}, {name: '北京', sobId: '2'}, {name: '广州', sobId: '3'}, {name: '深圳', sobId: '4'}]
  }, {
    name: 'a2',
    list: [{name: '上海1', sobId: '5'}, {name: '北京1', sobId: '6'}, {name: '广州1', sobId: '7'}, {name: '深圳1', sobId: '8'}]
  }];
  export default {
    data() {
      return {
        cities: cityOptions,
      };
    },
    methods: {
      // 全选反选的多选框
      handleCheckAllChange(index, e) {
        this.cities[index].checked = e
        if (e === false) this.cities[index].isIndeterminate = false;
        var childrenArray = this.cities[index].list;
        //  console.log(childrenArray)
        if (childrenArray)
          for (var i = 0, len = childrenArray.length; i < len; i++)
            childrenArray[i].checked = e
      },
      handleCheckedCitiesChange(index, sobId, e) {
        var childrenArray = this.cities[index].list;
        console.log(childrenArray);
        var tickCount = 0, unTickCount = 0, len = childrenArray.length;
        for (var i = 0; i < len; i++) {
          if (sobId === childrenArray[i].sobId) childrenArray[i].checked = e;
          if (childrenArray[i].checked === true) tickCount++;
          if (childrenArray[i].checked === false) unTickCount++
        }
        if (tickCount === len) {//二级全勾选
          this.cities[index].checked = true;
          this.cities[index].isIndeterminate = false
        } else if (unTickCount === len) {//二级全不勾选
          this.cities[index].checked = false;
          this.cities[index].isIndeterminate = false
        } else {
          this.cities[index].checked = false
          this.cities[index].isIndeterminate = true //添加一级不确定状态
        }
      },
      // 给返回的数据加是否选中的属性
      format(items) {
        return items.map(item => {
          const result = {...item, checked: false, isIndeterminate: false};
          if (item.list) {
            result.list = this.format(item.list)
          }
          return result
        })
      }
    },
    created() {


    },
    mounted() {
      this.cities = this.format(this.cities)
    }
  };
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">

</style>
